//
//  AddVC.m
//  XQContact
//
//  Created by ladystyle100 on 2017/8/29.
//  Copyright © 2017年 SyKingW. All rights reserved.
//

#import "AddVC.h"
#import "XQABManager.h"

@interface AddVC () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *lastNameTF;
@property (weak, nonatomic) IBOutlet UITextField *fristNameTF;
@property (weak, nonatomic) IBOutlet UITextField *organizationTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneLabelTF;

@property (nonatomic, copy) NSData *imgData;

@end

@implementation AddVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"View" style:UIBarButtonItemStylePlain target:self action:@selector(respondsToView)];
}

#pragma mark -- respondsTo

- (IBAction)respondsToSelectIm:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)respondsToAdd:(id)sender {
    XQABModel *model = [XQABModel new];
    model.firstName = self.fristNameTF.text;
    model.lastName = self.lastNameTF.text;
    model.organization = self.organizationTF.text;
    model.imgData = self.imgData;
    model.phoneArr = @[self.phoneTF.text];
    model.phoneLabelArr = @[self.phoneLabelTF.text];
    
    [[XQABManager manager] addContactWithModel:model] ?
    [SVProgressHUD showSuccessWithStatus:@"添加成功"]:
    [SVProgressHUD showSuccessWithStatus:@"添加失败"];
}

- (void)respondsToView {
    [[XQABManager manager] getAllContactWithCompletion:^(NSArray<XQABModel *> *modelArr) {
        for (XQABModel *model in modelArr) {
            NSLog(@"lastName = %@, firstName = %@", model.lastName, model.firstName);
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

#pragma mark -- UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *img = info[UIImagePickerControllerOriginalImage];
    self.imgData =  UIImagePNGRepresentation(img);
    if (!self.imgData) {
        self.imgData = UIImageJPEGRepresentation(img, 0.5);
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


@end















